package org.ruizhijie.topic.i.impl;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.ruizhijie.topic.TopicQueue;
import org.ruizhijie.topic.i.ISubcriber;
import org.ruizhijie.util.CharUtil;

public class OutPortSubcriberImpl implements ISubcriber{
	private Logger log = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
	private TopicQueue tq;
	private String topic;
	private String host;
	private int port;
	
	public OutPortSubcriberImpl(TopicQueue tq,String topic,String host,int port){
		this.tq = tq;
		this.topic = topic;
		this.host = host;
		this.port = port;
		
		this.subcribe();
	}

	@Override
	public void subcribe() {
		tq.subcribe(this,topic);
	}

	@Override
	public void unSubcribe() {
		tq.unSubcribe(this,topic);
	}

	@Override
	public void onMessage(byte[] msg) {
		log.info("-----topic:"+topic+"-----msg:"+CharUtil.bytesToHexString(msg));
		try {
			DatagramSocket ds = new DatagramSocket();
			ds.send(new DatagramPacket(msg, msg.length,InetAddress.getByName(host),port));
			ds.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
